package com.atguigu.gmall.realtime.app.dim;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.realtime.app.func.DimSinkFunction;
import com.atguigu.gmall.realtime.app.func.TableProcessFunction;
import com.atguigu.gmall.realtime.bean.TableProcess;
import com.atguigu.gmall.realtime.common.GmallConfig;
import com.atguigu.gmall.realtime.util.HbaseUtil;
import com.atguigu.gmall.realtime.util.MyKafkaUtil;
import com.ververica.cdc.connectors.mysql.source.MySqlSource;
import com.ververica.cdc.connectors.mysql.table.StartupOptions;
import com.ververica.cdc.debezium.JsonDebeziumDeserializationSchema;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.connector.kafka.source.KafkaSource;
import org.apache.flink.streaming.api.datastream.BroadcastConnectedStream;
import org.apache.flink.streaming.api.datastream.BroadcastStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.util.Collector;
import org.apache.hadoop.hbase.client.Connection;

import java.util.Properties;

/**
 * @author Felix
 * @date 2023/8/19
 */
public class MyApp extends BaseApp {
    
    public static void main(String[] args) throws Exception {
        MyApp app = new MyApp();
        app.base(args);
    }

    @Override
    public void biz(StreamExecutionEnvironment env) {
        //TODO 3.从kafka的主题中读取数据
        //3.1 声明消费的主题以及消费组
        String topic = "topic_db";
        String groupId = "dim_app_group";
        //3.2 创建消费者对象
        KafkaSource<String> kafkaSource = MyKafkaUtil.getKafkaSource(topic, groupId);
        //3.3 消费数据 封装为流
        DataStreamSource<String> kafkaStrDS
            = env.fromSource(kafkaSource, WatermarkStrategy.noWatermarks(), "Kafka Source");
        //TODO 4.对读取的数据进行类型转换以及简单的ETL   jsonStr->jsonObj
        SingleOutputStreamOperator<JSONObject> jsonObjDS = kafkaStrDS.process(
            new ProcessFunction<String, JSONObject>() {
                @Override
                public void processElement(String jsonStr, Context ctx, Collector<JSONObject> out) throws Exception {
                    //将json字符串转换为jsonObj
                    try {
                        JSONObject jsonObj = JSON.parseObject(jsonStr);
                        String type = jsonObj.getString("type");
                        if(!"bootstrap-start".equals(type)&&!"bootstrap-complete".equals(type)){
                            out.collect(jsonObj);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        );
        // jsonObjDS.print(">>>>");

        //TODO 5.使用FlinkCDC读取配置表中数据
        //5.1 创建MySqlSource
        Properties props = new Properties();
        props.setProperty("useSSL", "false");
        MySqlSource<String> mySqlSource = MySqlSource.<String>builder()
            .hostname("hadoop102")
            .port(3306)
            .databaseList("gmall0315_config") // set captured database
            .tableList("gmall0315_config.table_process_dim") // set captured table
            .username("root")
            .password("123456")
            .jdbcProperties(props)
            .serverTimeZone("Asia/Shanghai")
            .deserializer(new JsonDebeziumDeserializationSchema())
            .startupOptions(StartupOptions.initial())
            .build();

        //5.2 读取数据 封装为流
        DataStreamSource<String> mysqlStrDS
            = env.fromSource(mySqlSource, WatermarkStrategy.noWatermarks(), "mysql_source");

        //"op":"r":  {"before":null,"after":{"source_table":"user_info","sink_table":"dim_user_info","sink_family":"info","sink_columns":"id,login_name,name,user_level,birthday,gender,create_time,operate_time","sink_row_key":"id"},"source":{"version":"1.6.4.Final","connector":"mysql","name":"mysql_binlog_source","ts_ms":0,"snapshot":"false","db":"gmall0315_config","sequence":null,"table":"table_process_dim","server_id":0,"gtid":null,"file":"","pos":0,"row":0,"thread":null,"query":null},"op":"r","ts_ms":1692426976215,"transaction":null}
        //"op":"c"： {"before":null,"after":{"source_table":"aa","sink_table":"dim_a","sink_family":"info","sink_columns":"id,name","sink_row_key":"id"},"source":{"version":"1.6.4.Final","connector":"mysql","name":"mysql_binlog_source","ts_ms":1692427110000,"snapshot":"false","db":"gmall0315_config","sequence":null,"table":"table_process_dim","server_id":1,"gtid":null,"file":"mysql-bin.000004","pos":10907673,"row":0,"thread":null,"query":null},"op":"c","ts_ms":1692427110373,"transaction":null}
        //"op":"u": {"before":{"source_table":"aa","sink_table":"dim_a","sink_family":"info","sink_columns":"id,name","sink_row_key":"id"},"after":{"source_table":"aa","sink_table":"dim_a","sink_family":"info","sink_columns":"id,name,age","sink_row_key":"id"},"source":{"version":"1.6.4.Final","connector":"mysql","name":"mysql_binlog_source","ts_ms":1692427142000,"snapshot":"false","db":"gmall0315_config","sequence":null,"table":"table_process_dim","server_id":1,"gtid":null,"file":"mysql-bin.000004","pos":10908034,"row":0,"thread":null,"query":null},"op":"u","ts_ms":1692427142258,"transaction":null}
        //"op":"d": {"before":{"source_table":"aa","sink_table":"dim_a","sink_family":"info","sink_columns":"id,name,age","sink_row_key":"id"},"after":null,"source":{"version":"1.6.4.Final","connector":"mysql","name":"mysql_binlog_source","ts_ms":1692427178000,"snapshot":"false","db":"gmall0315_config","sequence":null,"table":"table_process_dim","server_id":1,"gtid":null,"file":"mysql-bin.000004","pos":10908422,"row":0,"thread":null,"query":null},"op":"d","ts_ms":1692427178485,"transaction":null}
        // mysqlStrDS.print(">>>");

        //5.3 将读取的数据进行类型转换  jsonStr->实体类对象
        SingleOutputStreamOperator<TableProcess> tableProcessDS = mysqlStrDS.process(
            new ProcessFunction<String, TableProcess>() {
                @Override
                public void processElement(String jsonStr, Context ctx, Collector<TableProcess> out) throws Exception {
                    //为了处理方便，先将当前jsonStr转换为jsonObj
                    JSONObject jsonObj = JSON.parseObject(jsonStr);
                    //获取对配置表进行的操作类型
                    String op = jsonObj.getString("op");
                    TableProcess tableProcess = null;
                    //判断是否为删除操作
                    if ("d".equals(op)) {
                        //删除操作：从before属性中获取配置信息
                        tableProcess = jsonObj.getObject("before", TableProcess.class);
                    } else {
                        //删除外的其它操作：从after属性中获取配置信息
                        tableProcess = jsonObj.getObject("after", TableProcess.class);
                    }
                    tableProcess.setOp(op);
                    out.collect(tableProcess);
                }
            }
        );

        // tableProcessDS.print(">>>");

        //TODO 6.根据配置流中的配置信息提前在hbase中创建表或者从hbase中将表删掉
        tableProcessDS = tableProcessDS.map(
            new RichMapFunction<TableProcess, TableProcess>() {
                private Connection conn;
                @Override
                public void open(Configuration parameters) throws Exception {
                    conn = HbaseUtil.getHbaseConnection();
                }

                @Override
                public void close() throws Exception {
                    HbaseUtil.closeHbaseConnection(conn);
                }

                @Override
                public TableProcess map(TableProcess tableProcess) throws Exception {
                    // 获取对配置表进行操作类型
                    String op = tableProcess.getOp();
                    //获取hbase中维度表的表名
                    String sinkTable = tableProcess.getSinkTable();
                    //获取hbase表中的列族
                    String sinkFamily = tableProcess.getSinkFamily();
                    //判断操作类型
                    if("c".equals(op)||"r".equals(op)){
                        //建表
                        HbaseUtil.createTable(conn, GmallConfig.HBASE_NAMESPACE,sinkTable,sinkFamily.split(","));
                    }else if("d".equals(op)){
                        //删表
                        HbaseUtil.dropTable(conn,GmallConfig.HBASE_NAMESPACE,sinkTable);
                    }else{
                        //先删表
                        HbaseUtil.dropTable(conn,GmallConfig.HBASE_NAMESPACE,sinkTable);
                        //再建表
                        HbaseUtil.createTable(conn, GmallConfig.HBASE_NAMESPACE,sinkTable,sinkFamily.split(","));
                    }
                    return tableProcess;
                }
            }
        );
        // tableProcessDS.print(">>>");
        //TODO 7.将配置流进行广播
        MapStateDescriptor<String, TableProcess> mapStateDescriptor
            = new MapStateDescriptor<String, TableProcess>("mapStateDescriptor",String.class,TableProcess.class);
        BroadcastStream<TableProcess> broadcastDS = tableProcessDS.broadcast(mapStateDescriptor);

        //TODO 8.将主流业务数据和广播流中配置信息进行关联
        BroadcastConnectedStream<JSONObject, TableProcess> connectDS = jsonObjDS.connect(broadcastDS);

        //TODO 9.对关联后的数据进行处理----过滤出维度数据
        SingleOutputStreamOperator<JSONObject> dimDS = connectDS.process(
            new TableProcessFunction(mapStateDescriptor)
        );
        //TODO 10.将维度流中数据写到hbase中
        dimDS.print(">>>");
        dimDS.addSink(new DimSinkFunction());
    }
}
